﻿/*
* Copyright 2012 Alliance Global Services, Inc. All rights reserved.
*
* Any redistribution or reproduction of part or all of the contents in any form is prohibited.
*
* You may not, except with our express written permission, distribute or commercially exploit the content.
* Nor may you transmit it or store it in any other form of electronic retrieval system.
*
* Class: EmailUtility
* 
* Purpose: <<This class has two functions.
*			1. ConfigureMailServer (string user, string pwd, string smtpAddr, int portNumber,bool enableSsl)
				This function will configure the mail server with the specified properties.
*			2. SendMail(string from, string to, string cc, string bcc, string subject, string body, string dirName, bool sendAsHTML, string mailPriority)
*				This functon will send the mail to the specified addresses		>>
* 
*/
using System;
using System.IO;
using System.Net.Mail;
using Ionic.Zip;

namespace AGSTestUtilities
{
    public class EmailUtility
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        public string SmtpAddress { get; set; }
        public int PortNumber { get; set; }
        public bool EnableSsl { get; set; }

        /// <summary>
        /// This function will configure the mail server with the specified properties.
        /// </summary>
        /// <param name="user">UserName</param>
        /// <param name="pwd">Password</param>
        /// <param name="smtpAddr">SmtpAddress</param>
        /// <param name="portNumber">PortNumber</param>
        /// <param name="enableSsl">EnableSsl [truw/false]</param>
        public void ConfigureMailServer(string user, string pwd, string smtpAddr, int portNumber, bool enableSsl)
        {
            UserName = user;
            Password = pwd;
            SmtpAddress = smtpAddr;
            PortNumber = portNumber;
            EnableSsl = enableSsl;
        }

        /// <summary>
        /// Sends the specified e-mail message to the specified recipients through an SMTP server. The message
        //  sender, recipients, subject, and message body are specified using System.String objects.
        /// </summary>
        /// <param name="from">From Address</param>
        /// <param name="to">To Address</param>
        /// <param name="cc">CC Address</param>
        /// <param name="bcc">BCC Address</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body of the Email</param>
        /// <param name="dirName">Path of the [Folder/File] to attach</param>
        /// <param name="sendAsHTML">Body of the email in Html format [true/false]</param>
        /// <param name="mailPriority">Priority of the email [Low,Normal,High]</param>
        public void SendMail(string from, string to, string cc, string bcc, string subject, string body, string dirName, bool sendAsHTML, string mailPriority)
        {
            // Instantiate a new instance of MailMessage
            MailMessage mMailMessage = new MailMessage();

            // Set the sender address of the mail message
             mMailMessage.From = new MailAddress(from);

            var toAddressLists = to.Split(';');
            foreach (var toAddress in toAddressLists)
            {
                // Set the recepient address of the mail message
                mMailMessage.To.Add(new MailAddress(toAddress));
            }
            
            // Check if the bcc value is null or an empty string
            if (!string.IsNullOrEmpty(bcc))
            {
                var bccLists = bcc.Split(';');
                foreach (var bccAddress in bccLists)
                {
                    // Set the Bcc address of the mail message
                    mMailMessage.Bcc.Add(new MailAddress(bccAddress));
                }
            }

            // Check if the cc value is null or an empty value
            if (!string.IsNullOrEmpty(cc))
            {
                var ccLists = cc.Split(';');
                foreach (var ccAddress in ccLists)
                {
                    // Set the CC address of the mail message
                    mMailMessage.CC.Add(new MailAddress(ccAddress));
                }
            }
            // Set the subject of the mail message
            mMailMessage.Subject = subject;
            // Set the format of the mail message body as HTML
            mMailMessage.IsBodyHtml = sendAsHTML;
            // Set the body of the mail message
            mMailMessage.Body = body;
            var attachedItems = dirName.Split(';');
            Attachment attach = null;
            foreach (var attachedItem in attachedItems)
            {
                //Attachment verification
                if (!String.IsNullOrEmpty(attachedItem))
                {
                    if (CheckForDir(attachedItem))
                    {
                        CreateZip(attachedItem);
                        System.Threading.Thread.Sleep(2000);
                        attach = new Attachment(attachedItem + ".zip");
                    }
                    else
                    {
                        attach = new Attachment(attachedItem);
                    }
                    mMailMessage.Attachments.Add(attach);
                }
            }
            try
            {
                // Set the priority of the mail message. If invalid priority is passed it will be defaulted to Normal
                mMailMessage.Priority = (MailPriority)Enum.Parse(typeof(MailPriority), mailPriority, true);
            }
            catch (ArgumentException)
            {
                mMailMessage.Priority = MailPriority.Normal;
            }

            // Instantiate a new instance of SmtpClient
            SmtpClient mSmtpClient = new SmtpClient();
            mSmtpClient.EnableSsl = EnableSsl;

            mSmtpClient.Host = SmtpAddress;
            mSmtpClient.Port = PortNumber;
            if (EnableSsl)
            {
                mSmtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
            }

            try
            {
                // Send the mail message
                mSmtpClient.Send(mMailMessage);
                System.Threading.Thread.Sleep(2000);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error Sending Mail");
                Console.WriteLine(ex.GetBaseException().ToString());
                throw;
            }
        }

        /// <summary>
        /// This method verifies whether the given path is a directory or not
        /// </summary>
        /// <param name="dirName">Path name to verify</param>
        /// <returns></returns>
        private bool CheckForDir(string dirName)
        {
            FileAttributes attr = File.GetAttributes(dirName);
            if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// This method creates a Zip file for a given path
        /// </summary>
        /// <param name="dirName">Name of the path where the directory exists</param>
        private void CreateZip(string dirName)
        {
            //Create an empty zip file
            using (ZipFile zip = new ZipFile())
            {
                zip.AddDirectory(dirName);
                zip.Save(dirName + ".zip");
            }
        }
    }
}
